package com.sservice.service.common;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

public class Authorization {

    /**
     * 返回当前Subject 对象
     *
     * @return
     */
    public static Subject getsubject() {
        return SecurityUtils.getSubject();
    }

    public static void main(String[] args) {
//        Digests.generateSalt(SALT_SIZE)
        Authorization authorization = new Authorization();
        authorization.annotation("classpath:shiro-role.ini", "zhang", "123456");
        //判断当前对象Subject 是否包含"role1"角色
        boolean hasRole = getsubject().hasRole("role1");
        if (hasRole) {
            System.out.println("当前用户Object,拥有role1角色");
        } else {
            System.out.println("当前用户Object,没有role1角色");
        }


        //检查当前对象Subject 是否包含"role1"角色且该角色拥有"user.add"权限[提示：当前用户Subject，不包含"user.add"权限，会提示UnauthorizedException异常]
        try {
            getsubject().checkPermissions("system:user:update", "system:user:delete");
            System.out.println("当前Subject 包含user.add权限");
            getsubject().checkPermission("user.delete");
            System.out.println("当前Subject 包含user.delete权限");
        } catch (UnauthorizedException e) {
            System.out.println("异常抛出：" + e.getMessage());
        }

    }

    /**
     * @param iniPath
     * @param username
     * @param password
     */

    public void annotation(String iniPath, String username, String password) {
        // 1、获取SecurityManager工厂，此处使用Ini配置文件初始化SecurityManager
        Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory(iniPath);
        // 2、得到SecurityManager实例 并绑定给SecurityUtils
        org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        // 3、得到Subject及创建用户名/密码身份验证Token（即用户身份/凭证）
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            // 4、登录，即身份验证
            subject.login(token);
        } catch (AuthenticationException e) {
            // 5、身份验证失败
            System.out.println("身份验证失败");
        }
    }

}